<template>
	<view class="container">
		<!-- #ifdef H5 -->
		<view style="text-align: center;margin-bottom: 50rpx;font-size: 18px;color: #616161;">微信小程序授权登录</view>
		<view>
			<u-button text="授权登录" @click="onJump" type="primary" shape="circle"></u-button>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				scheme: ''
			};
		},
		onLoad() {
			// #ifdef MP-WEIXIN
			this.mnpLogin();
			// #endif

			// #ifdef H5
			this.authLogin();
			// #endif

		},
		methods: {
			onJump() {
				location.href = this.scheme;
				this.getScheme();
			},
			// 查询Scheme码
			getScheme() {
				const timer = setInterval(() => {
					this.$H.get("login/schemeLogin", {
						scheme: this.scheme
					}).then(res => {
						if (res.code === 1) {
							uni.showToast({
								title: '登录成功'
							})

							this.$store.commit("login", res.result);
							uni.navigateBack();
							clearInterval(timer)
						}
					})
				}, 2000);
			},
			// H5登录
			authLogin() {
				this.$H.get("login/generateScheme").then(res => {
					if (res.code === 1) {
						this.scheme = res.result;
					}
				})
			},
			// 微信小程序登录
			mnpLogin() {
				uni.showLoading({
					title: "登录中"
				})
				let that = this;
				wx.login({
					success(res) {
						that.$H.post('login/mnpLogin', {
							code: res.code
						}).then(res => {
							if (res.code === 1) {
								let userInfo = res.result;
								that.$store.commit('login', userInfo);
								uni.navigateBack()
							}

							uni.hideLoading();
						});
					}
				})
			}
		}
	};
</script>

<style lang="scss">

</style>